
//
//  NewsDetailViewController.m
//  YiChat20160706
//
//  Created by 李政 on 16/7/7.
//  Copyright © 2016年 ZhiYou. All rights reserved.
//

#import "NewsDetailViewController.h"

#import "ImageTableViewCell.h"
#import "TextTableViewCell.h"

#import "CommentTableViewCell.h"

#import "CommentObject.h"

@interface NewsDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

{
    NSArray *commentArray;
    NSArray *dataArray;
}

@end

@implementation NewsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [_myTable registerNib:[UINib nibWithNibName:@"ImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"image"];
    [_myTable registerNib:[UINib nibWithNibName:@"TextTableViewCell" bundle:nil] forCellReuseIdentifier:@"text"];
    [_myTable registerNib:[UINib nibWithNibName:@"CommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"comment"];
    
    [self loadData];
}

- (void)loadData
{
    AFHTTPSessionManager *mgr = [NetTool getSessionManager];
    
    if (mgr)
    {
        [mgr GET:[NSString stringWithFormat:@"%@%@",SERVER_URL,_obj.source_url] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [NetTool hideIndicator];
            
            if (responseObject)
            {
                
                NSLog(@"-----%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
                
                NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                
                commentArray = [CommentObject mj_objectArrayWithKeyValuesArray:resultDic[@"comments"]];
                
                dataArray = resultDic[@"data"];
                
                NSLog(@"----%ld",dataArray.count);
                
                
                
                //刷新表
                
                [_myTable reloadData];
            }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [NetTool hideIndicator];
            
            [Util showAlertWithMessage:LOAD_FAIL confirmBlock:nil];
        }];
    }
}

- (float)getTextHeightWithString:(NSString *)str font:(UIFont *)font width:(float)width
{
    
    CGRect rect = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    
    return rect.size.height + 10;
}



#pragma mark UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    float height = 0;
    
    if (section == 0)
    {
        height = 76 + [self getTextHeightWithString:[NSString stringWithFormat:@"摘要:%@",_obj.intro] font:[UIFont systemFontOfSize:15] width:SCREEN_WIDTH - 20];
    }
    else
    {
        height = 40;
    }
    
    
    
    return height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *v = nil;
    
    if (section == 0)
    {
        UIView *headerBgView = [[UIView alloc] init];
        //headerBgView.backgroundColor = [UIColor redColor];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH - 20, 30)];
        titleLabel.text = _obj.news_title;
        titleLabel.font = [UIFont systemFontOfSize:18];
        [headerBgView addSubview:titleLabel];
        
        UILabel *sourceLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 45, 70, 21)];
        sourceLabel.text = _obj.source;
        sourceLabel.font = [UIFont systemFontOfSize:15];
        [headerBgView addSubview:sourceLabel];
        
        UILabel *authorLable = [[UILabel alloc] initWithFrame:CGRectMake(85, 45, 75, 21)];
        authorLable.text = [NSString stringWithFormat:@"%@/文",_obj.auther];
        authorLable.font = [UIFont systemFontOfSize:15];
        [headerBgView addSubview:authorLable];
        
        UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(165, 45, SCREEN_WIDTH - 175, 21)];
        timeLabel.font = [UIFont systemFontOfSize:15];
        timeLabel.textAlignment = NSTextAlignmentRight;
        
        timeLabel.text = _obj.time;
        
        [headerBgView addSubview:timeLabel];
        
        UILabel *introLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 71, SCREEN_WIDTH - 20, [self getTextHeightWithString:[NSString stringWithFormat:@"摘要:%@",_obj.intro] font:[UIFont systemFontOfSize:15] width:SCREEN_WIDTH - 20])];
        introLable.backgroundColor = [UIColor lightGrayColor];
        introLable.font = [UIFont systemFontOfSize:15];
        introLable.numberOfLines = 0;
        introLable.text = [NSString stringWithFormat:@"摘要:%@",_obj.intro];
        [headerBgView addSubview:introLable];
        
        
        headerBgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, CGRectGetMaxY(introLable.frame));
        
        v = headerBgView;
    }
    
    else
    {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, SCREEN_WIDTH-60, 30)];
        
        label.backgroundColor = [UIColor whiteColor];
        
        label.text = @"    热门跟帖";
        
        label.font = [UIFont systemFontOfSize:20];
        
        v = label;
        
    }
    return v;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    int count = 0;
    if (section == 0)
    {
        count = (int)dataArray.count;
    }
    else
    {
        count = (int)commentArray.count;
    }
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    float H = 0;
    
    if (indexPath.section == 0)
    {
        if ([dataArray[indexPath.row][@"data_type"] isEqualToString:@"2"])
        {
            float w = [dataArray[indexPath.row][@"image"][@"width"] floatValue];
            
            float h = [dataArray[indexPath.row][@"image"][@"height"] floatValue];
            
            float height = h * (SCREEN_WIDTH - 20) /w;
            
            H = height;
        }
        else
        {
            NSString *content = dataArray[indexPath.row][@"content"];
            
            float height = [self getTextHeightWithString:content font:[UIFont systemFontOfSize:15] width:SCREEN_WIDTH - 20] + 10;
            
            H = height;
        }
    }
    
    else
    {
        CommentObject *comment = commentArray[indexPath.row];
        
        
        float height = [self getTextHeightWithString:comment.info font:[UIFont systemFontOfSize:15] width:SCREEN_WIDTH - 20];
        
        H = height + 36;
    }
    
    
   
    
    return H;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static UITableViewCell *cell = nil;
    
    if (indexPath.section == 0)
    {
        if ([dataArray[indexPath.row][@"data_type"] isEqualToString:@"1"]) {
            
            TextTableViewCell *textCell = [tableView dequeueReusableCellWithIdentifier:@"text" forIndexPath:indexPath];
            
            textCell.textLabel.text = dataArray[indexPath.row][@"content"];
            
            textCell.textLabel.numberOfLines = 0;
            
            textCell.textLabel.font = [UIFont systemFontOfSize:15];
            
            cell = textCell;
        }else
        {
             ImageTableViewCell *imageCell = [tableView dequeueReusableCellWithIdentifier:@"image" forIndexPath:indexPath];
             
             
             NSString *urlStr = dataArray[indexPath.row][@"image"][@"source"];
             
            [imageCell.imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",SERVER_URL,urlStr]]];
             
             NSLog(@"-----%@",[NSString stringWithFormat:@"%@%@",SERVER_URL,urlStr]);
             
           //  imageCell.backgroundColor = [UIColor blueColor];
             
             cell = imageCell;
        }
    }
    
    
    else
    {
        CommentObject *comment = commentArray[indexPath.row];
        
        CommentTableViewCell *commentCell = [tableView dequeueReusableCellWithIdentifier:@"comment" forIndexPath:indexPath];
        
        commentCell.commentPeopleLabel.text = comment.name;
        
        commentCell.commentInfoLabel.text = comment.info;
        
        cell = commentCell;
    }

    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSLog(@"------%ld",indexPath.row);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
